<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body onload="init()">
    <button onclick="clickme()">有种点我试试</button>
    <button onclick="closeWorker()">关闭worker</button>
    <div id="clickResult"></div>
    <div id="result"></div>
    <script>
      //创建一个Worker对象，并向它传递将在新线程中执行的脚本url
      var worker = new Worker("worker.js");
      var arr = [
        "你竟然真的点了",
        "真乖",
        "你还来",
        "啊，你够了",
        "我要叫我大哥了",
        "再点我怕我死机了",
        "在这么下去webWorker要觉醒了",
        "准备迎接我大哥的怒火吧"
      ];
      var i = 0;
      function clickme() {
        document.getElementById("clickResult").innerHTML += arr[i] + "<br>";
        i++;
        if (i > 7) {
          i = 7;
        }
      }
      function closeWorker() {
        worker.terminate();
      }
      function init() {
        //接收worker传递过来的数据
        worker.onmessage = function(event) {
          document.getElementById("result").innerHTML += event.data + "<br/>";
        };
        worker.onerror(function(e) {
          console.log(
            [
              "ERROR: Line ",
              e.lineno,
              " in ",
              e.filename,
              ": ",
              e.message
            ].join("")
          );
        });
      }
    </script>
  </body>
</html>
